package com.tanhua.sso.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.api.HuanXinApi;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    public Map<String, Object> login(String phone, String code) {
        boolean isNew = false;
        String key = "CHECK_CODE:" + phone;
        String checkCode = redisTemplate.opsForValue().get(key);
        if (!StringUtils.equals(checkCode, code)) {
            //验证码发送错误
            return null;
        }
        redisTemplate.delete(key);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("mobile", phone);
        User user = userMapper.selectOne(wrapper);
        if (null == user) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));//对密码进行加密\
            //注册新用户
            userMapper.insert(user);
            isNew = true;
            //注册环信用户
            Boolean register = huanXinApi.register(user.getId());
            if (!register) {
                //注册环信失败,记录日志
                log.error("注册环信用户失败~ userId = " + user.getId());
            }
        }
        //生成token
        Long id = user.getId();
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12)) //设置过期时间，3秒后过期
                .compact();
        System.out.println(token);

//        向消息队列中发送id和登录时间
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("time", new Date(System.currentTimeMillis()));
            rocketMQTemplate.convertAndSend("tanhua-sso-login", map);
        } catch (MessagingException e) {
            log.error("登录消息发送错误+id: " + id, e);
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", token);
        map.put("isNew", isNew);
        return map;
    }

    public User queryUserByToken(String token) {
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
//            System.out.println(body); //{mobile=1333333333, id=2, exp=1605513392}
            Long id = Long.valueOf(body.get("id").toString());
            String redisKey = "tanhua-user-mobile-" + id;
            User user = new User();
            user.setId(id);
            if (redisTemplate.hasKey(redisKey)) {
                String mobile = redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                User u = this.userMapper.selectById(user.getId());
                String mobile = u.getMobile();
                user.setMobile(mobile);
                Long exp = Long.valueOf(body.get("exp").toString());
                Long timeOut = exp * 1000 - System.currentTimeMillis();
                redisTemplate.opsForValue().set(redisKey, mobile, timeOut);
            }
            return user;
        } catch (ExpiredJwtException e) {
            System.out.println("token已经过期！token=" + token);
        } catch (Exception e) {
            System.out.println("token不合法！token=" + token);
        }
        return null;
    }

}
